#include "Enemy.h"

#include "NiagaraFunctionLibrary.h"
#include "Demo/Component/DamageComponent.h"
#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetMathLibrary.h"

AEnemy::AEnemy()
{
	PrimaryActorTick . bCanEverTick = true;

	DamageComponent = CreateDefaultSubobject<UDamageComponent>(TEXT("DamageComponent"));
}

void AEnemy::BeginPlay()
{
	Super::BeginPlay();
}

void AEnemy::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	Counter += DeltaTime;
	if (Counter >= 0.5)
	{
		Counter = 0;
		DamageComponent -> Attack();
	}
	APawn* Player = UGameplayStatics::GetPlayerPawn(GetWorld(), 0);
	if (Player)
	{
		const FVector PlayerLocation = Player -> GetActorLocation();
		const FVector EnemyLocation = GetActorLocation();
		const FRotator LookAtRotation = UKismetMathLibrary::FindLookAtRotation(EnemyLocation, PlayerLocation);
		SetActorRotation(LookAtRotation);
		const FVector LerpLocation = FMath::VInterpTo(EnemyLocation, PlayerLocation, DeltaTime, 1);
		SetActorLocation(LerpLocation);
	}
}

void AEnemy::PlayAttackSound()
{
	UGameplayStatics::PlaySoundAtLocation(this, AttackSound, GetActorLocation());
}

void AEnemy::PlayAttackEffect()
{
	UNiagaraFunctionLibrary::SpawnSystemAttached(
		AttackEffect, GetRootComponent(), "",
		FVector::ZeroVector, FRotator::ZeroRotator,
		EAttachLocation::KeepRelativeOffset, true
	);
}
